package com.wjw.utils.sms;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.wjw.utils.HttpUtil;

/**
 * @desc 短信发送工具类
 * @author wjw 
 * @date 2016年11月24日下午5:38:54
 */
public final class SmsClient {

    /**
     * 日志对象
     */
    protected static Logger log = LoggerFactory.getLogger(SmsClient.class);
    
	/** 短信回执JSON格式 */
    private static final Pattern RESULT_PATTERN = Pattern.compile("^\\s*\\{\\s*\"state\"\\s*:\\s*(\\d+)\\s*,\\s*\"message\"\\s*:\\s*\"([^\"]*)\"",Pattern.MULTILINE);
	
	private String url;//短信发送服务器地址
	private String account;//账户
	private String password;//密码

	public SmsClient() {
		// TODO Auto-generated constructor stub
	}
	/** 构造器 */
	public SmsClient(String url,String account,String password) {
		// TODO Auto-generated constructor stub
		this.url=url;
		this.account=account;
		this.password=password;
	}
	
	/**  发送短信 */
	@SuppressWarnings("unchecked")
	public void send(final Sms sms) {
		Thread t=new Thread(new Runnable() {
			@Override
			public void run() {
				Map<String, String> queryParas = new HashMap<String, String>();
				try{
					queryParas.put("account", account);
					queryParas.put("password",password);
					queryParas.put("mobile", sms.getMobile());
					queryParas.put("content",sms.getContent());
					log.info(JSONObject.toJSONString(queryParas));
					String responseText = HttpUtil.post(url, queryParas);
					// 对结果进行解析
		            RestResult result = parseResult(responseText);
		            int state = result.getState();
					log.info("mobile:"+sms.getMobile()+"\t state:" + state);
					if (state == 2) {
						log.info("发送成功！");
					} else if (state == 4085) {
						log.error("发送失败，已经超过五次");
					} else {
						log.error("发送失败！");
					}
				}catch(Exception e){
					e.printStackTrace();
					log.error("网络异常！");
				}
			}
		});
		t.start();
	}
	
    /** 解析result     */
    private RestResult parseResult(String content) {
        RestResult result = null;
        Matcher matcher = RESULT_PATTERN.matcher(content);
        if (matcher.find()) {
            result = new RestResult();
            result.setState(Integer.parseInt(matcher.group(1)));
            result.setMsg(matcher.group(2));
        }
        return result;
    }
	
	 /**
     * 内部类短信结果实例
     */
    private static class RestResult {
        
        /** 错误码  */
        private int state;
        /** 消息  */
        private String msg;
        
		public int getState() {
			return state;
		}
		public void setState(int state) {
			this.state = state;
		}
		public String getMsg() {
			return msg;
		}
		public void setMsg(String msg) {
			this.msg = msg;
		}
		@Override
        public String toString() {
            return "RestResult [state=" + state + ", msg=" + msg + "]";
        }
    }
}
